import winreg
import ctypes


def set_system_proxy(enable: bool = True):
    """
    设置系统代理为 127.0.0.1:8080
    :param enable: True 为启用代理，False 为禁用代理
    """
    proxy_server = "127.0.0.1:8080"
    registry_path = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

    try:
        # 打开注册表键
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, registry_path, 0, winreg.KEY_WRITE)

        # 设置代理服务器地址
        winreg.SetValueEx(registry_key, "ProxyServer", 0, winreg.REG_SZ, proxy_server)

        # 启用或禁用代理
        winreg.SetValueEx(registry_key, "ProxyEnable", 0, winreg.REG_DWORD, 1 if enable else 0)

        # 关闭注册表键
        winreg.CloseKey(registry_key)

        # 刷新系统设置，使代理生效
        internet_setting = ctypes.windll.Wininet.InternetSetOptionW
        internet_setting(0, 37, 0, 0)  # 37 是 INTERNET_OPTION_SETTINGS_CHANGED
        internet_setting(0, 42, 0, 0)  # 42 是 INTERNET_OPTION_REFRESH

        print(f"系统代理已{'启用' if enable else '禁用'}：{proxy_server}")
    except Exception as e:
        print(f"设置代理失败：{e}")
